﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace PFMHandlers
{
     class PFMZipHandler:PFMHandler
    {
        public override byte[] Perform(PFMCandidate.Candidate aCandidate, byte[] baTarget)
        {
            //说明:若参数 baTarget 为 null,说明此为第一个处理器,
            //需要使用 PFMFileHandler 先把 aCandidate.Name 
            //所指定的文件处理为 byte[],在进行压缩; 
            //若参数 baTarget 不为 null,则直接压缩 baTarget
            //并把压缩结果返回。
            byte[] result=null;
            base.Perform(aCandidate, baTarget);
            baTarget= base.GetProcessingData(aCandidate, baTarget);
            using (MemoryStream ms = new MemoryStream())
            {
                using (ZipOutputStream zipStream = new ZipOutputStream(ms))
                {
                    ZipEntry entry = new ZipEntryFactory().MakeFileEntry(aCandidate.Name);
                    entry.DateTime = DateTime.Now;
                    entry.Size = baTarget.Length;
                    zipStream.PutNextEntry(entry);
                    zipStream.Write(baTarget, 0, baTarget.Length);
                    zipStream.CloseEntry();
                    zipStream.Finish();
                    result = ms.ToArray();
                    zipStream.Close();
                }
            }
            ChangeCandidateProcessedName(aCandidate);
            return result;
           
        }
        protected override void ChangeCandidateProcessedName(PFMCandidate.Candidate aCandidate)
        {
            base.ChangeCandidateProcessedName(aCandidate);
            aCandidate.ProcessedName += ".Zip";
        }
    }
}
